<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="关于线程状态Java线程状态:  New : 创建之后尚未启动 Runable : 包括Running和Ready，正在执行或者等待分配时间片 Waiting使用Object.wait()，Thread.join()，LockSupport.park() Timed Waiting使用Object.wait(time)，Thread.join(time)，LockSupport.park(time">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程知识">
<meta property="og:url" content="https://guodh.gitee.io/blog/2019/02/17/2019/Java%E7%BA%BF%E7%A8%8B%E7%9F%A5%E8%AF%86/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="关于线程状态Java线程状态:  New : 创建之后尚未启动 Runable : 包括Running和Ready，正在执行或者等待分配时间片 Waiting使用Object.wait()，Thread.join()，LockSupport.park() Timed Waiting使用Object.wait(time)，Thread.join(time)，LockSupport.park(time">
<meta property="og:locale">
<meta property="og:image" content="https://guodh.gitee.io/偏向锁.png">
<meta property="article:published_time" content="2019-02-17T04:42:02.000Z">
<meta property="article:modified_time" content="2020-01-28T14:19:30.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://guodh.gitee.io/偏向锁.png">

<link rel="canonical" href="https://guodh.gitee.io/blog/2019/02/17/2019/Java%E7%BA%BF%E7%A8%8B%E7%9F%A5%E8%AF%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>Java线程知识 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2019/02/17/2019/Java%E7%BA%BF%E7%A8%8B%E7%9F%A5%E8%AF%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java线程知识
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2019-02-17 12:42:02" itemprop="dateCreated datePublished" datetime="2019-02-17T12:42:02+08:00">2019-02-17</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-01-28 22:19:30" itemprop="dateModified" datetime="2020-01-28T22:19:30+08:00">2020-01-28</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="关于线程状态"><a href="#关于线程状态" class="headerlink" title="关于线程状态"></a>关于线程状态</h2><p>Java线程状态:</p>
<ul>
<li>New : 创建之后尚未启动</li>
<li>Runable : 包括Running和Ready，正在执行或者等待分配时间片</li>
<li>Waiting<br>使用Object.wait()，Thread.join()，LockSupport.park()</li>
<li>Timed Waiting<br>使用Object.wait(time)，Thread.join(time)，LockSupport.park(time)</li>
<li>Blocked : 程序等待进入同步区域</li>
<li>Terminated : 已终止状态</li>
</ul>
<a id="more"></a>

<p>为什么需要定义Java线程的状态？</p>
<p>线程的调度分为：协同式线程调度 和 抢占式线程调度</p>
<p>协同式现场调度，是线程执行完任务之后，自己通知操作系统来进行线程切换。<br>抢占式线程调度，是由操作系统来决定哪些线程被分配到了CPU时间片。</p>
<p>因此，Java为了实现抢占式线程调度就需要定义线程的状态，来方便CPU抉择哪些线程是能够被分配时间片的。所以即使线程处于Runable状态下，线程也不一定会运行，因为还需要CPU决定是否分配时间片。这往往和线程的优先度有关，但是优先度却是不准的东西。当然，也可以使用Thread.yield()来让出线程调度。</p>
<h2 id="关于锁释放"><a href="#关于锁释放" class="headerlink" title="关于锁释放"></a>关于锁释放</h2><p>线程的状态切换必然带来锁的问题。线程之间的通信、协作，必须有一个好的交互机制。</p>
<p>思考下，wait() 和 sleep() 设计的目的何在呢？</p>
<p>wait是线程之间的交流，而sleep则是自管自的调度。</p>
<p>来看下，由Synchronized所提供的monitor机制：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">ObjectMonitor() &#123;</span><br><span class="line">    _header       = NULL;</span><br><span class="line">    _count        = <span class="number">0</span>;</span><br><span class="line">    _waiters      = <span class="number">0</span>,</span><br><span class="line">    _recursions   = <span class="number">0</span>;</span><br><span class="line">    _object       = NULL;</span><br><span class="line">    _owner        = NULL;</span><br><span class="line">    _WaitSet      = NULL;</span><br><span class="line">    _WaitSetLock  = <span class="number">0</span> ;</span><br><span class="line">    _Responsible  = NULL ;</span><br><span class="line">    _succ         = NULL ;</span><br><span class="line">    _cxq          = NULL ;</span><br><span class="line">    FreeNext      = NULL ;</span><br><span class="line">    _EntryList    = NULL ;</span><br><span class="line">    _SpinFreq     = <span class="number">0</span> ;</span><br><span class="line">    _SpinClock    = <span class="number">0</span> ;</span><br><span class="line">    OwnerIsThread = <span class="number">0</span> ;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>wait会释放所持有的monitor锁，进入到 _WaitSet 中，同时处于 _EntryList 的对象能够获得monitor锁。</p>
<blockquote>
<p><a href="https://www.hollischuang.com/archives/2030">https://www.hollischuang.com/archives/2030</a></p>
</blockquote>
<p>还有一个视角，使用了LockSupport.park()会不会释放锁呢？<br>答案是，不会。</p>
<h2 id="内存模型："><a href="#内存模型：" class="headerlink" title="内存模型："></a>内存模型：</h2><p>首先，是由于CPU的速度远远大于磁盘，为了充分利用CPU的性能，CPU必须配置缓存。配置了缓存，同时在CPU的情况下，就存在了缓存的不一致的情况。</p>
<p>内存模型，是规定了一系列的规则，屏蔽不同硬件的底层指令集，让Java按照同样的规则来进行内存数据的读取。</p>
<p>既然讲到内存模型，就不得不提 volatile，因为正是 volatile 提现了最大的特性。</p>
<p>volatile 有两个作用：</p>
<ol>
<li>保证可见性<br>当有volatile修饰的变量，在某个工作线程被修改，它会使其他工作线程的缓存无效化，保证里其他的线程能够立马“看见”。但是呢，如果这个变量已经在栈上准备操作了，这是即使缓存无效化了，操作依旧被执行了。</li>
</ol>
<p>因此，使用 volatile 最好的场景如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">volatile</span> <span class="keyword">boolean</span> shutdown;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span>(!shutdown) &#123;</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>内存屏障<br>由于代码执行过程中存在指令重排序（CPU采用了允许将多条指令不按程序规定的顺序分开发送给各相应电路单元处理），会出现很多问题。</li>
</ol>
<p>有volatile修饰的变量，赋值后多执行了一个“load addl $0x0, (%esp)”操作，这个操作相当于一个内存屏障。</p>
<blockquote>
<p><a href="https://www.jianshu.com/p/ef8de88b1343">https://www.jianshu.com/p/ef8de88b1343</a></p>
</blockquote>
<h2 id="锁优化"><a href="#锁优化" class="headerlink" title="锁优化"></a>锁优化</h2><p>偏向锁 对象头记录线程Id<br>轻量级锁 CAS获取锁<br>重量级锁 monitor机制</p>
<p>当然，为了简化使用者对于语言使用的要求，Java的开发者对于Synchronized做了更多的优化，也是鼓励大家使用Synchronized。</p>
<p>将锁的程度分化，分为 偏向锁、轻量级锁、重量级锁。</p>
<img src="/偏向锁.png" alt="偏向锁.png"/>


    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E6%8A%80%E6%9C%AF/" rel="tag"># 技术</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2019/02/17/2019/%E5%88%B6%E4%BD%9C%E4%B8%80%E4%B8%AAspring-boot-starter/" rel="prev" title="制作一个spring-boot-starter">
      <i class="fa fa-chevron-left"></i> 制作一个spring-boot-starter
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2019/03/24/2019/Java%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/" rel="next" title="Java基础知识">
      Java基础知识 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81"><span class="nav-number">1.</span> <span class="nav-text">关于线程状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E9%94%81%E9%87%8A%E6%94%BE"><span class="nav-number">2.</span> <span class="nav-text">关于锁释放</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B%EF%BC%9A"><span class="nav-number">3.</span> <span class="nav-text">内存模型：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%94%81%E4%BC%98%E5%8C%96"><span class="nav-number">4.</span> <span class="nav-text">锁优化</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
